import router from '@/router';
import { VxeUI } from 'vxe-pc-ui';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import { hasAuth } from '@/plugins/permission';
import { useComponentState } from '@/composables/useComponentState';



export const useButtons = (options = {}) => {
  const { selectedCount, currentRow } = options;
  const { isChildrenMode } = useComponentState();
  
  return [
    {
      name: $t('common.action.back', '返回'),
      code: 'return_code',
      status: 'info',
      icon: 'Back',
      visible: computed(() => {
        return isChildrenMode.value;
      }),
    },
    {
      name: $t('common.action.delete', '删除'),
      code: 'delete_code',
      status: 'danger',
      icon: 'Delete',
      visible: hasAuth('admin:log:delete'),
      disabled: computed(() => {
        return selectedCount?.value === 0;
      }),
    },
    {
      name: $t('common.action.detail', '详情'),
      code: 'detail_code',
      status: 'info',
      icon: 'View',
      visible: hasAuth('admin:log:detail'),
      disabled: computed(() => {
        return selectedCount.value != 1;
      }),
    },
    {
      name: $t('menu.admin.log.action.clean', '清理'),
      code: 'clean_code',
      status: 'danger',
      icon: 'Delete',
      visible: hasAuth('admin:log:clean'),
      disabled: computed(() => {
        return false;
      }),
    },


    // 结束
  ];
};

export const useActions = (options = {}) => {
  const { API, gridRef, detailRef, } = options;
  


  // 统一确认对话框消息
  const confirmMessage = (action, ids) => {
    const confirmMessage = $t('common.message.confirm.general', '您确定要执行{action}', { params: { action },});
    return `${confirmMessage} ：${ids.join(', ')}`;
  };

  const actions = {
    deleteHandle({ rows }) {
      const ids = rows.map((item) => item.id);
      const content = confirmMessage($t('common.action.delete', '删除'), ids);
      VxeUI.modal.confirm(content).then((result) => {
        if (result === 'confirm') {
          API.delete({ id: ids })
            .then(() => {
              gridRef.value.commitProxy('query');
              ElMessage.success($t('common.message.success', '操作成功'));
            })
            .catch((error) => {
              ElMessage.success($t('common.message.error', '操作失败'));
            });
        }
      });
    },
    detailHandle({ rows }) {
      detailRef.value.show(rows[0].id);
    },
      // clean
      cleanHandle() {
        const selectedDate = ref('');
        // 对话框内容
        const messageContent = () =>
          h('div', { class: 'clean-dialog-content' }, [
            h(
              'p',
              '请选择需要清除截至到哪一天的数据，系统将会清除该日期之前的所有日志数据。如果不选任何日期，则默认清除所有日志数据。',
            ),
            h('p', { class: 'warning' }, '注意：数据清除后不可恢复！'),
            h(ElDatePicker, {
              modelValue: selectedDate.value,
              'onUpdate:modelValue': (value) => (selectedDate.value = value),
              type: 'date',
              placeholder: '选择截至日期',
              valueFormat: 'YYYY-MM-DD',
              style: 'width: 100%; margin-top: 15px;',
            }),
          ]);

        // 打开消息框
        ElMessageBox({
          title: '请选择截至日期',
          message: messageContent,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'clean-data-dialog',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              // 确认全部清除对话框
              ElMessageBox.confirm('您确认清除全部日志数据吗？', '提示', {
                type: 'warning',
              }).then(() => {
                // 执行数据清除操作
                API.clean({ date: selectedDate.value })
                  .then(({ data }) => {
                    ElMessage.success(`合计清除${data}条日志！`);
                    gridRef.value.commitProxy('query');
                  })
                  .catch(() => {
                    ElMessage.error('日志清除失败');
                  });
              });
            }
            done();
          },
        }).catch((error) => {
          if (error === 'cancel') {
            console.log('清除操作已取消');
          } else {
            console.error('清除日志时发生错误: ', error);
          }
        });
      },


    // 结束
  };

  // 行操作按钮的通用调用方法
  const dispatchAction = (code, row) => {
    switch (code) {
      case 'detail_handle':
        actions.detailHandle({ rows: [row] });
        break;
      default:
        console.warn(`Unknown action code: ${code}`);
    }
  };

  return { ...actions, dispatchAction };
};